package com.exampl.health.controller;

import com.exampl.health.entity.User;
import com.exampl.health.exception.LoginFailedException;
import com.exampl.health.exception.UserExistException;
import com.exampl.health.service.UserService;
import com.exampl.health.util.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 处理登录请求
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> login(String username, String password,
                                     HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 调用服务层进行登录验证
            User user = userService.login(username, password);

            // 登录成功，将用户信息存入session
            HttpSession session = request.getSession();
            session.setAttribute("currentUser", user);
            session.setMaxInactiveInterval(30 * 60); // 设置session有效期为30分钟

            result.put("success", true);
            result.put("message", "登录成功");
            result.put("user", user);

        } catch (LoginFailedException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统异常，请稍后重试");
        }

        return result;
    }

    /**
     * 处理注册请求
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> register(User user, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 参数验证
            if (!ValidationUtil.validateUser(user)) {
                result.put("success", false);
                result.put("message", "参数格式不正确");
                return result;
            }

            // 调用服务层进行注册
            User registeredUser = userService.register(user);

            // 注册成功，自动登录
            HttpSession session = request.getSession();
            session.setAttribute("currentUser", registeredUser);
            session.setMaxInactiveInterval(30 * 60);

            result.put("success", true);
            result.put("message", "注册成功");
            result.put("user", registeredUser);

        } catch (UserExistException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        } catch (IllegalArgumentException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统异常，请稍后重试");
        }

        return result;
    }

    /**
     * 检查用户名是否可用
     */
    @RequestMapping(value = "/checkUsername", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> checkUsername(String username) {
        Map<String, Object> result = new HashMap<>();

        try {
            boolean exists = userService.isUsernameExist(username);
            result.put("success", true);
            result.put("available", !exists);
            result.put("message", exists ? "用户名已存在" : "用户名可用");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统异常，请稍后重试");
        }

        return result;
    }

    /**
     * 检查邮箱是否可用
     */
    @RequestMapping(value = "/checkEmail", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> checkEmail(String email) {
        Map<String, Object> result = new HashMap<>();

        try {
            boolean exists = userService.isEmailExist(email);
            result.put("success", true);
            result.put("available", !exists);
            result.put("message", exists ? "邮箱已被注册" : "邮箱可用");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统异常，请稍后重试");
        }

        return result;
    }

    /**
     * 处理退出登录请求
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        // 清除session中的用户信息
        HttpSession session = request.getSession();
        session.removeAttribute("currentUser");
        session.invalidate();

        // 重定向到登录页面
        return "redirect:/login.jsp";
    }

    /**
     * 获取当前登录用户信息
     */
    @RequestMapping("/info")
    @ResponseBody
    public Map<String, Object> getCurrentUser(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser != null) {
            result.put("success", true);
            result.put("user", currentUser);
        } else {
            result.put("success", false);
            result.put("message", "用户未登录");
        }

        return result;
    }
}